package com.waverider.promotion.web.fg;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.iacrqq.util.DateUtil;
import com.waverider.promotion.biz.manager.FrontManager;
import com.waverider.promotion.biz.util.DateUtils;
import com.waverider.promotion.constants.PromotionConstants;
import com.waverider.promotion.domain.PromotionDO;
import com.waverider.promotion.domain.RebateModel;

public class FrontController implements Controller {
	private FrontManager frontManager;

	public void setFrontManager(FrontManager frontManager) {
		this.frontManager = frontManager;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String sellerNick = request
				.getParameter(PromotionConstants.SELLER_NICK);
		String shopId = request.getParameter(PromotionConstants.SHOP_ID);
		String width = request.getParameter(PromotionConstants.MODULE_WIDTH);

		if (validateParams(shopId, sellerNick))
			return new ModelAndView("error");
		List<PromotionDO> promotionDOList = frontManager
				.getPromotionByShopId(Long.valueOf(shopId));
		List<RebateModel> rebateModelList = frontManager.getOrderByShopId(Long
				.valueOf(shopId));

		Map<String, Object> context = new HashMap<String, Object>();
		context.put("promotionDOList", promotionDOList);
		context.put("rebateModelList", rebateModelList);
		context.put("width", width);
		context.put("dateUtil", new DateUtil());
		context.put("dateUtils", new DateUtils());
		context.put("dummyOrderCount", 0);
		if (promotionDOList.size() > 0)
			context.put("dummyOrderCount", promotionDOList.get(0)
					.getCurrentOrderCount().intValue()
					+ promotionDOList.get(0).getInitOrderCount().intValue());

		ModelAndView mv = new ModelAndView("fg/display");
		mv.addAllObjects(context);
		return mv;
	}

	private Boolean validateParams(String shopId, String sellerNick) {
		return StringUtils.isBlank(shopId) || StringUtils.isBlank(sellerNick) ? Boolean.TRUE
				: Boolean.FALSE;
	}
}
